import { useEffect } from 'react';
import { useLanguage } from '@/context/language-provider';

// 记录首页访问量
export function useHomePageVisit() {
  const { isInternational } = useLanguage();
  
  useEffect(() => {
    // 使用 localStorage 来避免重复计数
    const lastVisitTime = localStorage.getItem('lastHomeVisit');
    const currentTime = Date.now();
    
    // 如果是首次访问或距离上次访问超过1小时，则记录访问
    if (!lastVisitTime || (currentTime - parseInt(lastVisitTime)) > 3600000) {
      fetch(`/api/metrics?type=homepage${isInternational ? '&int=true' : ''}`, {
        method: 'POST',
      })
      .then(response => response.json())
      .catch(error => console.error('记录首页访问出错:', error));
      
      // 更新最后访问时间
      localStorage.setItem('lastHomeVisit', currentTime.toString());
    }
  }, [isInternational]);
}

// 记录考试页面访问量
export function useExamPageVisit(grade: string, examName: string, examDate: string) {
  const { isInternational } = useLanguage();
  
  useEffect(() => {
    // 生成考试唯一ID用于本地存储
    const examId = `${grade}_${examName}_${examDate}`;
    const lastVisitKey = `lastExamVisit_${examId}`;
    
    const lastVisitTime = localStorage.getItem(lastVisitKey);
    const currentTime = Date.now();
    
    // 如果是首次访问或距离上次访问超过1小时，则记录访问
    if (!lastVisitTime || (currentTime - parseInt(lastVisitTime)) > 3600000) {
      fetch(`/api/metrics?type=exam${isInternational ? '&int=true' : ''}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ grade, examName, examDate }),
      })
      .then(response => response.json())
      .catch(error => console.error('记录考试页面访问出错:', error));
      
      // 更新最后访问时间
      localStorage.setItem(lastVisitKey, currentTime.toString());
    }
  }, [grade, examName, examDate, isInternational]);
}

// 获取首页访问量
export async function getHomePageVisits(): Promise<number> {
  try {
    const response = await fetch('/api/metrics');
    const data = await response.json();
    return data.homepageVisits || 0;
  } catch (error) {
    console.error('获取首页访问量出错:', error);
    return 0;
  }
}

// 获取考试页面访问量
export async function getExamVisits(grade: string, examName: string, examDate: string): Promise<number> {
  try {
    // 构建查询参数
    const params = new URLSearchParams();
    params.append('grade', grade);
    params.append('examName', examName);
    params.append('examDate', examDate);
    
    const response = await fetch(`/api/metrics?${params.toString()}`);
    const data = await response.json();
    return data.visits || 0;
  } catch (error) {
    console.error('获取考试页面访问量出错:', error);
    return 0;
  }
}